package com.xltt.watchserver;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xltt.watchserver.bean.User;
import com.xltt.watchserver.blueth.BtBase;
import com.xltt.watchserver.blueth.BtServer;
import com.xltt.watchserver.utils.Logger;

import androidx.annotation.Nullable;

public class BTService extends Service implements BtBase.Listener{

    private void regBroadcast(Context context){
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        context.registerReceiver(mBluethRevice,filter);
    }
    private BroadcastReceiver mBluethRevice = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
            switch (blueState) {
                case BluetoothAdapter.STATE_TURNING_ON:
                    Logger.d("蓝牙正在打开");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Logger.d("蓝牙已经打开");
                    startSPPService();
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Logger.d("蓝牙正在关闭");
                    stopSPPService();
                    break;
                case BluetoothAdapter.STATE_OFF:
                    Logger.d("蓝牙已经关闭");
                    break;
            }
        }
    };

    private BtServer mBtServer;
    private void startSPPService(){
        if(mBtServer == null){
            mBtServer  = new BtServer(this);
        }
    }

    private void stopSPPService(){
        if(mBtServer != null){
            mBtServer.close();
            mBtServer = null;
        }
    }

    @Override
    public void socketNotify(int state, Object obj) {
        if(state == BtBase.Listener.CONNECTED){
            BluetoothDevice mBluetoothDevice = ((BluetoothDevice)obj);
            String address = mBluetoothDevice.getAddress();
            String name = mBluetoothDevice.getName();
            Logger.d("连接成功 ,蓝牙名称 = " + name + ",地址 = " + address);
        }else if(state == BtBase.Listener.DISCONNECTED){
            Logger.d("连接断开");
        }else if(state == BtBase.Listener.MSG){
            parseData(obj.toString());
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Logger.d("onBind()");
        return null;
    }

    @Override
    public void onCreate() {
        Logger.d("onCreate(),注册蓝牙广播开关监听");
        regBroadcast(this);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.d("onStartCommand()");
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null){
            Toast.makeText(this,"bluetooth adapter is null",Toast.LENGTH_SHORT).show();
            return super.onStartCommand(intent, flags, startId);
        }
        startSPPService();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Logger.d("onDestroy()");
        super.onDestroy();
    }

    /**
     * 解析客户端数据
     * @param msg
     */
    private void parseData(String msg){
        Logger.d("parseData()收到消息，内容 = " + msg);
        if(TextUtils.isEmpty(msg)){
            return;
        }
        final User user = new Gson().fromJson(msg, User.class);
        if(user == null){
            Logger.d("json数据转对象失败 ");
            return;
        }
        String userName = user.getUsername();
        String password = user.getPassword();
        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)){
            Logger.d("账号或密码为空");
            return;
        }
        Settings.Global.putString(getContentResolver(),User.USER_NAME, userName);
        Settings.Global.putString(getContentResolver(),User.PASSWORD, password);
        Settings.Global.putString(getContentResolver(),"watch_bind_enabled", 1 + "");
    }

}
